package com.kaishengit.web;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


import com.kaishengit.dao.UserDao;
import com.kaishengit.entity.User;
public class LoginServlet extends HttpServlet{

	private static final long serialVersionUID = 1L;
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		req.getRequestDispatcher("/WEB-INF/views/index.jsp").forward(req, resp);
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String name = req.getParameter("name");
		String password = req.getParameter("password");
		User user = new UserDao().findUserByNameAndPassword(name, password);
		if(name == null || "".equals(name) || password == null || "".equals(password)) {
			req.getRequestDispatcher("/WEB-INF/views/index.jsp?code=10002").forward(req, resp);
			return;
		}else if(user == null) {
			req.getRequestDispatcher("/WEB-INF/views/index.jsp?code=10001").forward(req, resp);
		}else {
			HttpSession session = req.getSession();
			session.setAttribute("user", user);
			String where = (String) session.getAttribute("where");
			if(where != null) {
				resp.sendRedirect(where);
				session.removeAttribute("where");
			}else {
				req.getRequestDispatcher("prod.jspx").forward(req, resp);
			}
		}
	}
}
